//
//  WDGroMoreTrackManager.m
//  WDGroMore
//
//  Created by YeJary on 2025/5/15.
//

#import "WDGroMoreTrackManager.h"
#import "WDGroMoreThinkingManager.h"
#import "UMAnalytics.h"
#import "WDGroMoreBADSignalManager.h"
#import "BMSOpMergeEventBuilder.h"
#import "WDBMS.h"
#import "BMSKeychain.h"
#import "BMSInitializer.h"

@implementation WDGroMoreTrackManager

+ (NSDictionary *)trackOptionsOnlySendBMS {
    return @{
        BMS_TRACK_DISABLE_THINKING: @([BMSInitializer shared].launchModel.content.firstObject.sdk_bms_to_ta),
        BMS_TRACK_DISABLE_UM: @(YES),
        BMS_TRACK_DISABLE_ADJUST: @(NO),
        BMS_TRACK_DISABLE_BMS:@(YES)
    };
}

+ (void)setup {
    // 初始化各个埋点 SDK
    [[WDGroMoreThinkingManager manager] thinkingConfig];
    
    [[UMAnalytics manager]initUMSDK];
    
    [[WDGroMoreBADSignalManager shareInstance]BADSignalInit]; //巨量引擎
    
    NSString *accountID = [BMSKeychain WDKeychainGetUUID]; //先初始化 SDK再登录 TA SDK
    [TDAnalytics login:accountID];
}

+ (void)track:(NSString *)event
       params:(NSDictionary *)params
        dType:(NSString *)dType
         desc:(NSString *)desc
      options:(NSDictionary *)options
{
    if (!event.length) return;

    NSDictionary *safeParams = [self dictionaryByRemovingNilFrom:params];
    NSDictionary *safeOptions = [self dictionaryByRemovingNilFrom:options];

    BOOL sendThinking = [safeOptions[BMS_TRACK_DISABLE_THINKING] boolValue];
    BOOL sendUM       = [safeOptions[BMS_TRACK_DISABLE_UM] boolValue];
    BOOL sendBMS      = [safeOptions[BMS_TRACK_DISABLE_BMS] boolValue];
    BOOL sendAdjust   = [safeOptions[BMS_TRACK_DISABLE_ADJUST] boolValue];

    // ThinkingAnalytics
    if (sendThinking) {
        [[WDGroMoreThinkingManager manager] thinkingTrackEventWithKey:event jsonStr:safeParams];
    }

    // 友盟
    if (sendUM) {
        [UMAnalytics umcEvent:event params:safeParams];
    }

    // BMS
    if (sendBMS) {
        NSDictionary *bmsEvent = nil;

        if ([dType isEqualToString:BMS_DTYPE_USER_OPERATION]) {
            bmsEvent = [BMSOpMergeEventBuilder event_userOpWithAct:event description:desc];

        } else if ([dType isEqualToString:BMS_DTYPE_USER_ACTION]) {
            bmsEvent = [BMSOpMergeEventBuilder event_userActionWithAct:event
                                                             description:desc
                                                                  tab1:safeParams[BMS_PARAM_TAB1]
                                                                  tab2:safeParams[BMS_PARAM_TAB2]
                                                                  tab3:safeParams[BMS_PARAM_TAB3]
                                                                  tabN:@{}];

        } else if ([dType isEqualToString:BMS_DTYPE_AD_ACTION]) {
            bmsEvent = [BMSOpMergeEventBuilder event_adActionWithAct:event
                                                                desc:desc
                                                                tab1:safeParams[BMS_PARAM_TAB1]
                                                                tab2:safeParams[BMS_PARAM_TAB2]
                                                                tab3:safeParams[BMS_PARAM_TAB3]
                                                              adType:safeParams[BMS_PARAM_AD_TYPE]];

        } else if ([dType isEqualToString:BMS_DTYPE_PURCHASE]) {
            bmsEvent = [BMSOpMergeEventBuilder event_iapSuccessWithProductId:safeParams[BMS_PARAM_PDI]
                                                                 productName:safeParams[BMS_PARAM_PDN]
                                                                  amountCent:[safeParams[BMS_PARAM_PAMT] integerValue]
                                                                     orderId:safeParams[BMS_PARAM_ODN]
                                                                 productType:safeParams[BMS_PARAM_PDT]];

        } else if ([dType isEqualToString:BMS_DTYPE_USER_INFO]) {
            bmsEvent = [BMSOpMergeEventBuilder event_userInfoWithPlatform:safeParams[BMS_PARAM_PLATFORM]
                                                                       os:safeParams[BMS_PARAM_OS]
                                                                     idfa:safeParams[BMS_PARAM_IDFA]
                                                                     idfv:safeParams[BMS_PARAM_IDFV]
                                                                     imei:safeParams[BMS_PARAM_IMEI]
                                                               android_id:safeParams[BMS_PARAM_ANDROIDID]
                                                                      mac:safeParams[BMS_PARAM_MAC]
                                                                     oaid:safeParams[BMS_PARAM_OAID]
                                                                       dm:safeParams[BMS_PARAM_DM]
                                                                       ct:safeParams[BMS_PARAM_CT]
                                                                    ym_id:safeParams[BMS_PARAM_YMID]];
        }

        if (bmsEvent) {
            [[BMSOpMergeReporter shared] addEvent:bmsEvent];
        }
    }

    // Adjust
    if (sendAdjust) {
        // [AdjustManager trackEvent:event withParameters:safeParams];
    }
}

+ (void)setUserID:(NSString *)userID {
    if (userID.length == 0) return;
    
    // Thinking
    [TDAnalytics login:userID];
    
    // UMeng
    [MobClick profileSignInWithPUID:userID];
    
    // Adjust（如有支持）
    // [AdjustManager setUserID:userID];
}

+ (void)registerGlobalProperties:(NSDictionary *)properties {
    if (!properties.count) return;
    
    // Thinking
    //    [[ThinkingAnalyticsSDK sharedInstance] registerSuperProperties:properties];
    
    // 友盟
    //    [MobClick registerSuperProperty:properties];
}

+ (void)clearGlobalProperties {
    //    [[ThinkingAnalyticsSDK sharedInstance] clearSuperProperties];
    // 友盟暂不支持清空所有 SuperProperty，只能覆盖
    //    [MobClick registerSuperProperty:@{}];
}

#pragma mark ----- private method ------------

+ (NSDictionary *)dictionaryByRemovingNilFrom:(NSDictionary *)dict {
    if (!dict) return @{};
    
    NSMutableDictionary *filtered = [NSMutableDictionary dictionaryWithCapacity:dict.count];
    for (id key in dict.allKeys) {
        id value = dict[key];
        if (key && value && value != [NSNull null]) {
            filtered[key] = value;
        } else {
            // 可选：日志输出
            NSLog(@"[TrackManager] ⚠️ 过滤掉 nil key=%@ value=%@", key, value);
        }
    }
    return [filtered copy];
}

@end
